<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\finance;

use app\command\BaseWork;
use app\model\ClientAccountModel;
use app\service\finance\statement\StatementService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

class StatementStatWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('statement_stat_work');
        $this->setDescription('生成结算数据脚本')
            ->addArgument('media_id', Argument::REQUIRED, '媒体id')
            ->addArgument('stat_month', Argument::OPTIONAL, '月份')
            ->addArgument('account_id', Argument::OPTIONAL, '账户id');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('生成结算数据开始');
        $mediaId = intval($input->getArgument('media_id'));
        $accountId = intval($input->getArgument('account_id'));
        $where = [];
        if ($accountId) {
            $where[] = ['id', '=', $accountId];
        }
        $month = intval($input->getArgument('stat_month') ?: date('Ym', strtotime('-1 month')));
        $accounts = (new ClientAccountModel())->where($where)->where('media_id', $mediaId)->select();
        foreach ($accounts as $account) {
            try {
                $service = new StatementService($account, $month);
                // 初始化服务
                if (! $service->initStat() || ! $service->saveStat()) {
                    throw new \Exception($service::getError(0));
                }
                $this->getOutputMessage('生成结算数据成功：' . $account->getAttr('advertiser_id'));
            } catch (\Exception $e) {
                $this->getOutputMessage('生成结算数据失败：' . $account->getAttr('advertiser_id') . $e->getMessage());
            }
        }
        $this->getOutputMessage('生成结算数据结束');
    }
}
